<!-- subpkg_consult/room/index.vue -->
<script setup>
	import { ref } from 'vue'
	import { storeToRefs } from 'pinia'
	// import { io } from 'socket.io-client' // 不支持微信小程序
	import { io } from '@hyoga/uni-socket.io'
	import dayjs from 'dayjs'
	import { useUserStore } from '@/stores/user.js'
	import patientInfo from './components/patient-info.vue'
	import notifyInfo from './components/notify-info.vue'
	import messageInfo from './components/message-info.vue'
	import prescriptionInfo from './components/prescription-info.vue'
	import roomStatus from './components/room-status.vue'
	import rateInfo from './components/rate-info.vue'
	import { orderDetailApi } from '@/services/consult.js'
	const props = defineProps({
		orderId: String,
	})
	const { token, userId } = storeToRefs(useUserStore())
	const messageList = ref([])
	const socket = io('https://consult-api.itheima.net', {
		auth: { token: `Bearer ${token.value}` },
		query: { orderId: props.orderId },
		transports: ['websocket', 'polling'],
		timeout: 5000,
	})
	socket.on('chatMsgList', ({ code, data }) => {
		refreshTrigger.value = false
		if (code !== 10000) return
		const tempList = []
		data.forEach(({ createTime, items }, index) => {
			if (index === 0) lastTime.value = createTime
			tempList.push(
				{
					msgType: 31,
					msg: { content: createTime },
					id: createTime,
				},
				...items
			)
		})
		if (tempList.length === 0) return uni.utils.toast('没有更多历史消息了...')
		messageList.value.unshift(...tempList)
	})
	socket.on('receiveChatMsg', (message) => {
		socket.emit('updateMsgStatus', message.id)
		messageList.value.push(message)
	})
	const orderDetail = ref({})
	const getOrderDetail = async () => {
		const { code, data, message } = await orderDetailApi(props.orderId)
		if (code !== 10000) return uni.utils.toast(message)
		orderDetail.value = data
	}
	getOrderDetail()
	socket.on('statusChange', getOrderDetail)
	const textMessage = ref('')
	const onInputConfirm = () => {
		socket.emit('sendChatMsg', {
			from: userId.value,
			to: orderDetail.value?.docInfo?.id,
			msgType: 1,
			msg: {
				content: textMessage.value,
			},
		})
		textMessage.value = ''
	}
	const onImageButtonClick = () => {
		if (orderDetail.value.status !== 3) {
			return uni.utils.toast('医生当前不在线！')
		}
		uniCloud.chooseAndUploadFile({
			type: 'image',
			count: 1,
			extension: ['.jpg', '.png', '.gif'],
			success: ({ tempFiles }) => {
				const picture = {
					id: tempFiles[0].lastModified,
					url: tempFiles[0].url,
				}
				socket.emit('sendChatMsg', {
					from: userId,
					to: orderDetail.value.docInfo?.id,
					msgType: 4,
					msg: picture,
				})
			},
		})
	}
	const refreshTrigger = ref(false)
	const lastTime = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))
	const onPullDownRefresh = () => {
		refreshTrigger.value = true
		socket.emit('getChatMsgList', 20, lastTime.value, props.orderId)
	}
</script>

<template>
	<view class="room-page">
		<roomStatus
			:status="orderDetail.status"
			:statusValue="orderDetail.statusValue"
			:countdown="orderDetail.countdown"
		></roomStatus>
		<scroll-view
			refresher-enabled
			@refresherrefresh="onPullDownRefresh"
			:refresher-triggered="refreshTrigger"
			refresher-background="#f2f2f2"
			scroll-y
			style="flex: 1; overflow: hidden"
		>
			<view class="message-container">
				<!-- 此处将来填充更多代码... -->
				<template v-for="message in messageList" :key="message.id">
					<patientInfo
						v-if="message.msgType === 21"
						:info="message.msg.consultRecord"
					></patientInfo>
					<notifyInfo v-if="message.msgType >= 31" :type="message.msgType">
						{{ message.msg.content }}
					</notifyInfo>
					<messageInfo
						v-if="message.msgType <= 4"
						:type="message.msgType"
						:info="message"
					></messageInfo>
					<prescriptionInfo
						v-if="message.msgType === 22"
						:info="message.msg.prescription"
					></prescriptionInfo>
					<rateInfo
						:hasEvaluate="false"
						v-if="message.msgType === 23"
						:order-id="props.orderId"
						:doctor-id="orderDetail.docInfo?.id"
					></rateInfo>
					<rateInfo
						:evaluateDoc="message.msg.evaluateDoc"
						:hasEvaluate="true"
						v-if="message.msgType === 24"
					></rateInfo>
				</template>
			</view>
		</scroll-view>

		<!-- 发送消息 -->
		<view class="message-bar">
			<template v-if="true">
				<uni-easyinput
					:disabled="orderDetail.status !== 3"
					v-model="textMessage"
					:clearable="false"
					:input-border="false"
					placeholder-style="font-size: 32rpx; color: #c3c3c5;"
					placeholder="问医生"
					@confirm="onInputConfirm"
				/>
				<view class="image-button" @click="onImageButtonClick">
					<uni-icons size="40" color="#979797" type="image"></uni-icons>
				</view>
			</template>
			<button v-else class="uni-button">咨询其它医生</button>
		</view>
	</view>
</template>

<style lang="scss">
	@import './index.scss';
</style>
